package com.fudan.adse.service.impl;

import com.fudan.adse.dao.UserRoleDao;
import com.fudan.adse.domain.po.Role;
import com.fudan.adse.domain.po.User;
import com.fudan.adse.domain.po.UserExample;
import com.fudan.adse.exception.Asserts;
import com.fudan.adse.grpc.UserGrpc;
import com.fudan.adse.grpc.UserQuery;
import com.fudan.adse.grpc.UserResponse;
import com.fudan.adse.mbg.mapper.UserMapper;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jerry Zhang
 * create: 2022-11-22 15:30
 */
@Slf4j
@GrpcService
public class UserGrpcServiceImpl extends UserGrpc.UserImplBase {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public void loadUserByUsername(UserQuery request, StreamObserver<UserResponse> responseObserver) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(request.getUsername());
        List<User> users = userMapper.selectByExample(example);
        if (users == null || users.isEmpty()) {
            Asserts.fail("username 不存在");
        } else {
            List<Role> roles = userRoleDao.getRoleList(users.get(0).getId());
            UserResponse response = UserResponse.newBuilder()
                    .setUuid(users.get(0).getId().toString())
                    .setUsername(users.get(0).getUsername())
                    .setPassword(users.get(0).getPassword())
                    .setStatus(users.get(0).getStatus())
                    .addAllRoles(roles.stream().map(Role::getRoleName).collect(Collectors.toList()))
                    .build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    }
}
